<template>
  <div class="app-container">
	  
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="团号" prop="numbers">
        <el-input v-model="queryParams.numbers" placeholder="请输入团号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="线路名称" prop="lineNames">
        <el-input v-model="queryParams.lineNames" placeholder="请输入线路名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <!-- <el-form-item label="线路id" prop="lineId">
        <el-input v-model="queryParams.lineId" placeholder="请输入线路id" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item> -->
      <el-form-item label="业务类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择业务类型">
              <el-option v-for="dict in this.getDictDatas(DICT_TYPE.team_orde_type)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="团联系人" prop="blocksName">
        <el-input v-model="queryParams.blocksName" placeholder="请输入组团联系人" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item><br/>
      <el-form-item label="抵达日期" prop="arriveDate">
        <!-- <el-date-picker v-model="queryParams.arriveDate" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" /> -->
				 <el-date-picker  v-model="queryParams.arriveDate[0]"  type="date" value-format="yyyy-MM-dd HH:mm:ss"  placeholder="选择日期"></el-date-picker>								
      </el-form-item>
     <!-- <el-form-item label="抵达时间" prop="arriveTime">
        <el-date-picker v-model="queryParams.arriveTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item> -->
     <!-- <el-form-item label="返程日期" prop="returnDate">
        <el-date-picker v-model="queryParams.returnDate" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item> -->
      <!-- <el-form-item label="返程时间" prop="returnTime">
        <el-date-picker v-model="queryParams.returnTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['team:orde:create']">新增</el-button>
      </el-col>
	  <!-- <el-col :span="1.5">
	    <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm2(undefined)"
	               v-hasPermi="['team:orde:create']">添加车队和酒店</el-button>
	  </el-col> -->
	  <el-col :span="1.5">
	    <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="lineNameHB('合并')"
	               v-hasPermi="['team:orde:create']">合并团</el-button>
	  </el-col>
	  <el-col :span="1.5">
	    <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="lineNameHB('解除合并')"
	               v-hasPermi="['team:orde:create']">解除合并</el-button>
	  </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['team:orde:export']">导出</el-button>
      </el-col> -->
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
	<el-table ref="tableRef7" row-key="id"   :span-method="mergeCells" v-loading="loading"  :key="tableke"  border  v-if="showTable" :data="list"  >
		<el-table-column  type="selection"  width="55"></el-table-column>
		<el-table-column label="团号" align="center" prop="numbers"  width="120"/>
		<el-table-column label="线路名称" align="center" prop="lineNames"  width="140">
			<template v-slot="scope">
				<span>{{ scope.row.lineNames }}</span>
			</template>
		</el-table-column>
		<el-table-column label="团联系人" align="center" prop="blocksName" />
		<!-- <el-table-column label="酒店" width="200">
					<template v-slot="scope">
						<div v-if="scope.row.date4">
							<span v-for="(item,index) in scope.row.date4">{{item}}<br /></span>
						</div>	
						
					</template>
		</el-table-column> -->
		<el-table-column label="车队" width="200">
					<template v-slot="scope">
				<div v-if="scope.row.date3">
					<span>
						<el-link type="primary"   @click="clickFleet(scope.row)">
							 {{scope.row.date3}} ：合并号：{{scope.row.date2}}
						</el-link>
					</span>
				</div>
				<div v-else>
					<el-link type="danger" @click="clickFleet(scope.row)">选择车队</el-link>
				</div>	
					</template>
		</el-table-column>
			<!-- <el-table-column label="k" align="center" prop="k" /> -->
			<el-table-column label="抵达日期" align="center" prop="arriveDate" width="100" >
				<template v-slot="scope">
					<span>{{parseTime(scope.row.arriveDate,'{m}-{d} {h}:{i}') }}</span>
				</template>
			</el-table-column>
		 <el-table-column v-for="(item,index) in date" :key="item"  :label="item">
					<template v-slot="scope">
						<div>
							<span v-if="luodiReturn(scope.row.arriveDate,index)==0" style="color: rgb(230, 162, 60);">{{scope.row.arrX[index]}}<br/>
							</span>
							<span v-else>{{scope.row.arrX[index]}}<br/></span>
							<!-- <span>{{scope.row.arrA[index]}}</span> -->
							<div v-if="scope.row.arrX[index]!=''">
								<el-link v-if="scope.row.arrA[index]!=''" type="primary"  @click="clickHotel(scope.row,index)">{{scope.row.arrA[index]}}</el-link>
								<el-link v-else type="danger" @click="clickHotel(scope.row,index)">选择酒店</el-link>
							</div>
						</div>
					</template>
		 </el-table-column>
		
		<el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
			<template v-slot="scope">
				<el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
									 v-hasPermi="['team:orde:update']">修改</el-button>
		<el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
							 v-hasPermi="[' team:orde:details']">详情</el-button>		 
				<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
									 v-hasPermi="['team:orde:delete']">删除</el-button>
				 
			</template>
		</el-table-column>
	</el-table>
		
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <OrdeForm ref="formRef" @success="getList" />
	<!-- 添加车队和酒店(设置)-->
	<hotelAndHoteForm ref="formRef2" @success="getList" />
    </div>
</template>

<script>
import * as OrdeApi from '@/api/team/orde';
import OrdeForm from './OrdeForm.vue';
import hotelAndHoteForm from './hotelAndHoteForm.vue';
import moment from 'moment';
import Sortable from 'sortablejs';// 引入 SortableJS 的样式，如果你需要的话
export default {
  name: "Orde",
  components: {
          OrdeForm,hotelAndHoteForm
  },
  data() {
    return {
		tableke:0,
		showTable:true,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
              // 总条数
        total: 0,
      // 团队订单列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
	    date:[1, 2 ],
      // 查询参数
      queryParams: {
                    pageNo: 1,
            pageSize: 10,
        numbers: null,
        lineNames: null,
        lineId: null,
        type: null,
        blocksName: null,
        arriveDate: [moment().subtract(3, 'day').format('YYYY-MM-DD HH:mm:ss'),],
        arriveTime: [],
        returnDate: [],
        returnTime: [],
      },
	  spanArr:[]
     };
  },
  mounted() {
    this.initSortable();
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      try {
		this.loading = true;
		//this.queryParams.arriveDate[0]=moment().startOf('day').format('YYYY-MM-DD HH:mm:ss');
		this.queryParams.arriveDate[1]=this.getDateAfter30Days(this.queryParams.arriveDate[0])
		console.log(this.queryParams);
        const res = await OrdeApi.getOrdePage(this.queryParams);
        //this.list = res.data.list;
        this.total = res.data.total;
		console.log(this.queryParams);
		this.updateDateRange()
		this.tex(res.data.list)
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
	/** 酒店车队选择操作 */
	//选择车队
	clickFleet(row){
		 this.$refs["formRef2"].opentow(row);
	},
	//选择酒店
	clickHotel(row,index){
		let this_=this;
		console.log("选择酒店",row)
		console.log(moment(this_.queryParams.arriveDate[0]).format('YYYY-MM-DD'),index)
		//计算相差的天数
		const dateT=this.calculateDays(moment(this_.queryParams.arriveDate[0]).format('YYYY-MM-DD'),moment(row.arriveDate).format('YYYY-MM-DD'))
		let dateIndex=index-dateT
		console.log("计算相差的天数",dateT)
	    console.log("插入的酒店数组下标",dateIndex)
		this.$refs["formRef2"].openHotel(row,dateIndex);
	},
	//计算落地日下标
	luodiReturn(RarriveDate,index){
		const dateT=this.calculateDays(moment(this.queryParams.arriveDate[0]).format('YYYY-MM-DD'),moment(RarriveDate).format('YYYY-MM-DD'))
		return index-dateT
	},
	openForm2() {
		let selectedRows= this.$refs["tableRef"].selection;
		if (selectedRows.length== 0) {
		  this.$modal.msgError("请先勾选数据！！！");
		  return;
		}
	  this.$refs["formRef2"].open(selectedRows);
	},
	//开启行拖拽
	initSortable() {
	     const el = this.$refs.tableRef7.$el.querySelector('.el-table__body-wrapper > table > tbody'); // 获取tbody元素
	     Sortable.create(el, {
	       onEnd: (evt) => {
	         const { oldIndex, newIndex } = evt;
	         /* const movedRow = this.tableData.splice(oldIndex, 1)[0]; // 从旧位置移除并获取该行数据
	         this.tableData.splice(newIndex, 0, movedRow); // 将该行数据插入到新位置
	         this.handleRowDragged(); // 可选：调用方法处理拖拽完成后的逻辑，如更新后端数据等。 */
	       }
	     });
	   },
	async lineNameHB(type){
		try {
			//合并团
			//判断是否选择车队了
			let selectedRows= this.$refs["tableRef7"].selection;
			if(selectedRows.length==0)return this.$modal.msgError("请选择"+type+"的团！！" );
			if(type=="合并"){
				let rens=  selectedRows.filter(item => item.date3 == null && item.date3 == undefined)
				console.log("判断是否选择车队了",rens.length)
				if(rens.length!=0)return this.$modal.msgError("存在车队未选择，请先选择车队在合并！！" );
			
				//获取最小的排序日期
				let dateX=selectedRows.sort((a, b) => new Date(a.date5) - new Date(b.date5))[0];
				
				console.log("获取最小的排序日期",dateX)
				selectedRows=selectedRows.map(item => ({
					id: item.id,
					numbers:item.numbers,
					lineNames: item.lineNames, 
					date1: item.date1,
					date2: selectedRows[0].id,
					date5:dateX.date5,
				}));
				console.log(selectedRows)
				//判断合并规则 时间和路线一致
				/* const lineNames = selectedRows[0].lineNames;
				const firstDate = moment(selectedRows[0].date1).format('YYYY-MM-DD'); // 格式化日期为yyyymmdd
				let res= selectedRows.every(item => item.lineNames === lineNames && moment(item.date1).format('YYYY-MM-DD') === firstDate);
				console.log(lineNames,firstDate)
				if(!res) return this.$modal.msgError("日期或者线路名称不一致无法合并！！" ); */
			
			}else{
				selectedRows=selectedRows.map(item => ({
					id: item.id,
					numbers:item.numbers,
					lineNames: item.lineNames, 
					date1: item.date1,
					date2: 0,
					date5:moment(item.arriveDate).format('YYYY-MM-DD HH:mm:ss'),
				}));
			}
			await this.$modal.confirm('是否确认'+type+'选择的数据项?')
			try {
				// 合并数据更新
				await OrdeApi.updateBatch(selectedRows);
				await this.getList();
				this.$modal.msgSuccess(type+"成功");
				this.dialogVisible = false;
			} catch {}
			
		}finally {
          this.loading = false;
        }
	},
	/** 提交按钮 */
	 submitForm(type) {
		
	},
	  reloadTable() {
	      //this.showTable = false; // 先移除表格组件
	      this.$nextTick(() => { // 确保 DOM 更新完成后再添加回来
	        //this.showTable = true; 
			
			 setTimeout(() => {
			         console.log('这个动作被延迟了2秒');
			         // 这里放置你的延迟执行代码
			          this.initSortable();
			       }, 1000); // 2000毫秒 = 2秒
	      });
	    },
	//解析拼成日历
	tex(list){
			  this.list=[]
			  let this_=this
			  list.forEach((item,index) => {
				  item.date3=JSON.parse(item.date3)
				  item.date4=JSON.parse(item.date4)
				  //落地日生成数组长度
				  item.arrX=new Array(this.date.length).fill("")
				  //酒店生成数组长度
				  item.arrA=new Array(this.date.length).fill("")
				  let aa=moment(item.arriveDate).format('YYYY-MM-DD');
				
				  //计算相差日期
				  const dateT=this_.calculateDays(moment(this_.queryParams.arriveDate[0]).format('YYYY-MM-DD'),moment(item.arriveDate).format('YYYY-MM-DD'))
				  if (!item.date32) return null;
				  const xing=JSON.parse(item.date32)
				  const aing=JSON.parse(item.date31)
				  //console.log("this.计算相差日期",dateT)
				  //循环游日
				  for (let i = 0; i < xing.length; i++) {
				     item.arrX[Number(dateT+i)]=xing[i]
					 item.arrA[Number(dateT+i)]=aing[i]
				  }
			  })
			  //重新排序 把合并的排在一起
			  this.paix(list)
			  this.getSpanArr(list)
			  this.list=list
			  this.tableke+=1
			  this.$nextTick(() => { // 确保 DOM 更新完成后再添加回来
				this.initSortable();
			  });
			  console.log("this.list",this.list)
	},
	//重新排序
	paix(list){
		/* this.list.sort((a, b) => {
		      // 首先按照日期升序排序
		      const dateComparison = moment(a.date1).format('YYYY-MM-DD') - moment(b.date1).format('YYYY-MM-DD');
		      if (dateComparison !== 0) {
		        return dateComparison;
		      }
		      // 如果日期相同，则按照type升序排序
		       return a.date2.localeCompare(b.date2);
		    }); */
		list.sort((a, b) => {
		      const dateA = moment(a.date5).format('YYYY-MM-DD');
		      const dateB = moment(b.date5).format('YYYY-MM-DD');
		      if (dateA < dateB) return -1;
		      if (dateA > dateB) return 1;
			  return a.date2.localeCompare(b.date2);
		      
		});
		 console.log("重新排序",list);
		 
	},
	//时间格式转换
	formattedDate() {
	      const date = new Date();
	      const year = date.getFullYear();
	      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
	      const day = String(date.getDate()).padStart(2, '0');
	      return `${year}-${month}-${day}`;s
	    },
	//计算天差
	calculateDays(date11,date22){
			   const date1 = new Date(date11);
			    const date2 = new Date(date22);
				
			    const diffTime = Math.abs(date2 - date1);
			    return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
	},
	//合并单元格
	mergeCells({ row, column, rowIndex, columnIndex }) {
		 if (columnIndex === 4) {   //我要修改的控件位于表格第一列，所以下标是0，其他按需修改
		   if( row.date2!="0"){
				const _row = this.spanArr[rowIndex];
				const _col = _row > 0 ? 1 : 0;
				console.log(row, '_col');
				return {
				  rowspan: _row, //行
				  colspan: _col //列
				};
			}
		 }
	},
	getSpanArr(data) {
	  this.spanArr = [];
	  for (var i = 0; i < data.length; i++) {
		if (i === 0) {
		  this.spanArr.push(1);
		  this.pos = 0;
		} else {
		  // 判断当前元素与上一个元素是否相同
		  if (data[i].date2 === data[i - 1].date2 && data[i].date2) {
			 this.spanArr[this.pos] += 1;
			 this.spanArr.push(0);
		  } else {
			 this.spanArr.push(1);
			 this.pos = i;
		  }
		}
	  }
	  console.log(this.spanArr, ' this.spanArr');
	},
	updateDateRange() {
	      let dateRange = [];
		  let aa=moment(this.queryParams.arriveDate[0]).format('YYYY-MM-DD');
	      if (this.queryParams.arriveDate[0] && this.queryParams.arriveDate[1]) {
	        const start = new Date(aa);
	        const end = new Date(this.queryParams.arriveDate[1]);
	        const diffTime = Math.abs(end - start);
	        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
	        for (let i = 0; i <= diffDays; i++) {
	          const currentDate = new Date(start);
	          currentDate.setDate(start.getDate() + i);
	          dateRange.push(currentDate.toISOString().split('T')[0]); // 只获取日期部分，不包含时间
	        }
			this.date=dateRange
			 console.log("日期数组",  dateRange)
		  }
	} ,
	//计算30天后的结束日期方法
	getDateAfter30Days(date) {
	    // 确保输入的是有效的日期字符串
	    if (!date) return null;
	    
	    // 使用moment计算30天后的日期 
	    const thirtyDaysLater = moment(date).add(27, 'days').format('YYYY-MM-DD HH:mm:ss');
	    return thirtyDaysLater;
	},
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除团队订单编号为"' + id + '"的数据项?')
      try {
       await OrdeApi.deleteOrde(id);
       await this.getList();
       this.$modal.msgSuccess("删除成功");
      } catch {}
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有团队订单数据项?');
      try {
        this.exportLoading = true;
        const data = await OrdeApi.exportOrdeExcel(this.queryParams);
        this.$download.excel(data, '团队订单.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
              }
};
</script>
<style scoped>
.custom-background {
  background-color: #f0f9eb; /* 你想要的颜色 */
}
</style>
